package com.chatplus.application.web;

import com.chatplus.application.web.filter.MyXssFilter;
import jakarta.servlet.DispatcherType;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.util.HashMap;
import java.util.Map;

/**
 * XSS过滤拦截器配置
 */
@Configuration
@ConditionalOnProperty(value = "xss.enabled", havingValue = "true")
public class XSSFilterConfiguration {

    public static final String CONFIG_KEY_ROOT = "xss.filter";

    @Bean
    @ConfigurationProperties(CONFIG_KEY_ROOT)
    public XSSFilterProperties xssFilterProperties() {
        return new XSSFilterProperties();
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    public FilterRegistrationBean xssFilterRegistration(XSSFilterProperties xssFilterProperties) {
        String enabled = xssFilterProperties.getEnabled() + "";
        String patterns = StringUtils.trimToEmpty(xssFilterProperties.getPatterns());
        String excludes = StringUtils.trimToEmpty(xssFilterProperties.getExcludes());
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new MyXssFilter());
        registration.addUrlPatterns(StringUtils.split(patterns, ","));
        registration.setName("xssFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("enabled", enabled);
        initParameters.put("excludes", excludes);
        registration.setInitParameters(initParameters);
        return registration;
    }

    public static class XSSFilterProperties {

        private Boolean enabled = false;
        /**
         * 排除链接（多个用逗号分隔）
         */
        private String excludes;
        /**
         * 匹配链接（多个用逗号分隔）
         */
        private String patterns;

        public Boolean getEnabled() {
            return enabled;
        }

        public void setEnabled(Boolean enabled) {
            this.enabled = enabled;
        }

        public String getExcludes() {
            return excludes;
        }

        public void setExcludes(String excludes) {
            this.excludes = excludes;
        }

        public String getPatterns() {
            return patterns;
        }

        public void setPatterns(String patterns) {
            this.patterns = patterns;
        }

    }

}
